/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package htmlunit.code;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.UnexpectedPage;
import com.gargoylesoftware.htmlunit.WebClient;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import sun.misc.BASE64Encoder;
import htmlunit.mode.*;

/**
 *
 * @author TiTa
 */
public class tai_hinh_htmlunit {
   static String ten_file;
    Hinh h_taihinh=new Hinh();
    static String  name;
    public tai_hinh_htmlunit(String name1){
        this.name=name1;
    }

    tai_hinh_htmlunit() {
       
    }
    public void chuoi_hinh(String url) {
             //String[] arr;
     // arr = url.split("/");
    try{
         WebClient client = new WebClient(BrowserVersion.FIREFOX_24);
          client.getOptions().setUseInsecureSSL(true);
    UnexpectedPage imagePage = client.getPage(url);
    
    BASE64Encoder encoder = new BASE64Encoder();
    String base64data = encoder.encode(inputStreamToByteArray(imagePage.getWebResponse().getContentAsStream()));
  //  System.out.println("<img src=\"data:image/png;base64,"+base64data.replaceAll("\r?\n","")+"\" />");

    } catch (Exception e) {
        e.printStackTrace();
    }
 
}
   
private static byte[] inputStreamToByteArray(InputStream is) throws IOException {
    
    // xu ly chuoi is
    int dodai_is=is.toString().length();
     ten_file=is.toString().substring(28, dodai_is);
  //  System.out.println(ten_file);
    //
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;
   
    byte[] data = new byte[16384];
    while ((nRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }
    buffer.flush();
     byte[] response=buffer.toByteArray();
     FileOutputStream fos = new FileOutputStream("C://hinh_facebook//"+name+ten_file+".jpg");//"C://hinh_facebook//pepe_hinh2014.jpg"
   //   FileOutputStream fos = new FileOutputStream("C://hinh_facebook//sssss.jpg");
    // System.out.println("ten_file"+name.toString()+ten_file.toString()+".jpg");//loi
     
    fos.write(response);
    fos.close();

    return buffer.toByteArray();
   
}
public String duong_dan_hinh(){
    return "C:/hinh_facebook/"+name+ten_file+".jpg";
}
public String ten_hinh(){
    return name+ten_file+".jpg";

}
      public static void main (String args[])  {
              tai_hinh_htmlunit th=new tai_hinh_htmlunit();
             th.chuoi_hinh("https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-prn2/t1.417/1425772_487978061299939_2086665576_n.jpg");
      }
    
}
